<template>
  <div class="article-editor-container">
    <el-row :gutter="20">
      <!-- 文章内容编辑区域 -->
      <el-col :span="16">
        <div class="editor-wrapper">
          <div class="editor-toolbar-sticky">
            <!-- 编辑器类型切换 -->
            <div class="editor-switch">
              <el-radio-group v-model="editorType" size="small" @change="handleEditorTypeChange">
                <el-radio-button label="rich">富文本编辑器</el-radio-button>
                <el-radio-button label="markdown">Markdown编辑器</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <!-- 富文本编辑器 -->
          <editor v-if="editorType === 'rich'" v-model="form.articleContent"/>

          <!-- Markdown编辑器 (使用 md-editor-v3) -->
          <rich-text-editor v-if="editorType === 'markdown'" v-model="form.articleContent" :height="editorHeight"
                            :language="'zh-CN'"
                            :placeholder="'请输入文章内容...'" @change="handleContentChange"/>
        </div>
      </el-col>

      <!-- 右侧面板区域 -->
      <el-col :span="8">
        <!-- 面板切换标签 -->
        <div class="panel-tabs">
          <div class="tab-switch">
            <el-button-group>
              <el-button :type="activePanel === 'form' ? 'primary' : 'default'" @click="switchPanel('form')"
                         size="small">
                <el-icon>
                  <Document/>
                </el-icon>
                信息编辑
              </el-button>
              <el-button :type="activePanel === 'ai' ? 'primary' : 'default'" @click="switchPanel('ai')" size="small">
                <el-icon>
                  <MagicStick/>
                </el-icon>
                AI建议
                <el-badge v-if="AIarticleData.length > 0" :value="AIarticleData.length" class="ai-badge"/>
              </el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 文章信息编辑面板 -->
        <div v-show="activePanel === 'form'" class="metadata-wrapper panel">
          <el-form ref="articleFormRef" :model="form" :rules="rules" label-width="100px" label-position="top">
            <el-form-item label="文章标题" prop="articleTitle">
              <el-input v-model="form.articleTitle" placeholder="请输入文章标题" maxlength="100" show-word-limit/>
            </el-form-item>

            <el-form-item label="文章封面图" prop="articleImg">
              <image-upload v-model="form.articleImg" :tip="'建议尺寸: 1200 x 675px'"/>
            </el-form-item>

            <el-form-item label="文章简介" prop="articleExcerpt">
              <el-input v-model="form.articleExcerpt" type="textarea" placeholder="请输入文章简介" maxlength="200"
                        show-word-limit :autosize="{ minRows: 3, maxRows: 6 }"/>
            </el-form-item>

            <el-form-item label="文章分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" filterable class="w-full">
                <el-option v-for="category in categoryList" :key="category.categoryId" :label="category.categoryName"
                           :value="category.categoryId"/>
              </el-select>
            </el-form-item>

            <el-form-item label="文章状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in bk_status" :key="dict.value" :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="编辑器类型">
              <el-select v-model="form.editorType" placeholder="请选择编辑器类型" class="w-full"
                         @change="handleFormEditorTypeChange">
                <el-option label="富文本编辑器" value="rich"/>
                <el-option label="Markdown编辑器" value="markdown"/>
              </el-select>
            </el-form-item>
          </el-form>

          <div class="form-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitting">
              {{ id ? '更新' : '提交' }}
            </el-button>
            <el-button type="success" @click="submitAI" :loading="aiLoading">
              <el-icon>
                <MagicStick/>
              </el-icon>
              AI文章优化
            </el-button>
          </div>
        </div>

        <!-- AI建议面板 -->
        <div v-show="activePanel === 'ai'" class="ai-suggestions-wrapper panel">
          <div class="ai-panel-header">
            <h3>AI文章优化建议</h3>
            <el-button v-if="AIarticleData.length > 0" type="default" size="small" @click="switchPanel('form')">
              返回编辑
            </el-button>
          </div>

          <template v-if="AIarticleData.length">
            <div class="ai-suggestions-content">
              <el-card shadow="hover" class="suggestion-card">
                <el-timeline>
                  <el-timeline-item v-for="(suggestion, index) in AIarticleData" :key="index"
                                    :timestamp="`建议 ${index + 1}`" placement="top" type="primary">
                    <div class="suggestion-text">{{ suggestion }}</div>
                  </el-timeline-item>
                </el-timeline>
              </el-card>
            </div>
          </template>

          <template v-else-if="aiLoading">
            <div class="ai-loading">
              <!-- <el-icon class="is-loading" :size="30">
                <Loading />
              </el-icon> -->
              <div class="cards">
                <div class="card">
                  <div class="face front"></div>
                  <div class="face back"></div>
                </div>
                <div class="card">
                  <div class="face front"></div>
                  <div class="face back"></div>
                </div>
                <div class="card">
                  <div class="face front"></div>
                  <div class="face back"></div>
                </div>
                <div class="card">
                  <div class="face front"></div>
                  <div class="face back"></div>
                </div>
              </div>
              <p>正在生成优化建议，请稍候...</p>
            </div>
          </template>
          <template v-else>
            <div class="ai-empty">
              <el-empty description="暂无优化建议"/>
              <p>点击"AI文章优化"按钮获取建议</p>
            </div>
          </template>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, reactive, toRefs, computed, onMounted, getCurrentInstance, nextTick, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {getArticle, addArticle, updateArticle} from "@/api/bk/article";
import {listCategory} from "@/api/bk/category";
import RichTextEditor from '@/components/MarkdownEditor/index.vue';
import {getArticleOptimizationAPI} from "@/api/ai/index.js";
import {
  Document,
  MagicStick,
  Loading
} from '@element-plus/icons-vue';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
// import { marked } from 'marked';

// 组件设置
const route = useRoute();
const router = useRouter();
const {proxy} = getCurrentInstance();
const articleFormRef = ref(null);
const submitting = ref(false);
const aiLoading = ref(false);
const activePanel = ref('form'); // 默认显示表单面板

// 编辑器类型
const editorType = ref('rich');
// 编辑器高度，动态计算以适应容器
const editorHeight = computed(() => {
  // 返回适合容器的高度，留出工具栏和其他元素的空间
  return window.innerHeight - 240; // 200px(原高度) + 额外的40px作为安全边距
});

// 字典数据
const {bk_status} = proxy.useDict('bk_status');

// 从路由查询参数获取文章ID
const id = computed(() => route.query.id);

// 响应式数据
const state = reactive({
  form: {
    articleTitle: '',
    articleContent: '',
    articleImg: '',
    articleExcerpt: '',
    categoryId: null,
    status: null, // 默认为草稿
    editorType: 'rich', // 默认使用富文本编辑器
  },
  rules: {
    articleTitle: [
      {required: true, message: "文章标题不能为空", trigger: "blur"},
      {max: 100, message: "标题长度不能超过100个字符", trigger: "blur"}
    ],
    articleContent: [
      {required: true, message: "文章内容不能为空", trigger: "blur"}
    ],
    categoryId: [
      {required: true, message: "请选择文章分类", trigger: "change"}
    ],
    articleExcerpt: [
      {max: 200, message: "简介长度不能超过200个字符", trigger: "blur"}
    ]
  }
});

const articleData = ref({
  content: '',
  title: '',
  excerpt: '',
});

const AIarticleData = ref([]);

const {form, rules} = toRefs(state);
const categoryList = ref([]);

// 切换面板
const switchPanel = (panel) => {
  activePanel.value = panel;
};

// 处理编辑器类型切换（顶部Radio按钮）
const handleEditorTypeChange = (newType) => {
  console.log('切换编辑器类型为:', newType);
  editorType.value = newType;
  form.value.editorType = newType;
};

// 处理表单中编辑器类型选择器的变化
const handleFormEditorTypeChange = (newType) => {
  console.log('表单编辑器类型切换为:', newType);
  editorType.value = newType;
  form.value.editorType = newType;
};

// ai优化提交
const submitAI = async () => {
  if (!form.value.articleContent.trim()) {
    return proxy.$modal.msgError('请先编写文章内容再使用AI优化');
  }

  aiLoading.value = true;
  activePanel.value = 'ai'; // 切换到AI建议面板

  articleData.value.content = form.value.articleContent;
  articleData.value.title = form.value.articleTitle;
  articleData.value.excerpt = form.value.articleExcerpt;

  try {
    const response = await getArticleOptimizationAPI(articleData.value);
    if (response && response.data) {
      AIarticleData.value = response.data.suggestions;
      console.log(AIarticleData.value)
      proxy.$modal.msgSuccess('AI优化建议生成成功');
    }
  } catch (error) {
    console.error('获取文章优化建议失败:', error);
    proxy.$modal.msgError('获取文章优化建议失败');
  } finally {
    aiLoading.value = false;
  }
};

// 监听编辑器类型变化，确保同步
watch(editorType, (newVal) => {
  console.log('编辑器类型监听变化:', newVal);
  if (form.value.editorType !== newVal) {
    form.value.editorType = newVal;
  }
});

// 监听表单中编辑器类型变化，确保同步
watch(() => form.value.editorType, (newVal) => {
  console.log('表单编辑器类型监听变化:', newVal);
  if (editorType.value !== newVal) {
    editorType.value = newVal;
  }
});

// 处理Markdown内容变化
const handleContentChange = (newContent) => {
  // 可以在这里添加额外的处理逻辑，比如自动保存等
  console.log('Markdown内容已更新');
};

const handleUpdateExcerpt = (excerpt) => {
  console.log('收到更新摘要:', excerpt);
  // 更新到表单或状态库
};

// 方法
const fetchArticleData = async () => {
  if (!id.value) return;

  try {
    const response = await getArticle(id.value);
    if (response && response.data) {
      // 使用Object.assign避免丢失响应式属性
      Object.assign(form.value, response.data);
      // 设置编辑器类型，确保同步
      const articleEditorType = response.data.editorType || 'rich';
      editorType.value = articleEditorType;
      form.value.editorType = articleEditorType;

      console.log('加载文章数据，编辑器类型:', articleEditorType);
    }
  } catch (error) {
    console.error('获取文章失败:', error);
    proxy.$modal.msgError('获取文章数据失败');
  }
};

const fetchCategories = async () => {
  try {
    const response = await listCategory({categoryStatus: null});
    if (response && response.rows) {
      categoryList.value = response.rows;
    }
  } catch (error) {
    console.error('获取分类失败:', error);
    proxy.$modal.msgError('获取分类数据失败');
  }
};

const submitForm = async () => {
  await nextTick();

  articleFormRef.value.validate(async (valid) => {
    if (!valid) {
      return proxy.$modal.msgError('请检查表单填写是否正确');
    }

    // 确保编辑器类型在提交前正确设置
    form.value.editorType = editorType.value;

    console.log('提交表单，编辑器类型:', form.value.editorType);
    console.log('完整表单数据:', form.value);

    try {
      submitting.value = true;
      const requestMethod = id.value ? updateArticle : addArticle;
      const response = await requestMethod(form.value);

      proxy.$modal.msgSuccess(id.value ? '更新成功' : '创建成功');
      handleCancel();
    } catch (error) {
      console.error('表单提交失败:', error);
      proxy.$modal.msgError(id.value ? '更新失败' : '创建失败');
    } finally {
      submitting.value = false;
    }
  });
};

const handleCancel = () => {
  router.push('/article/article');
};

const resetForm = () => {
  articleFormRef.value?.resetFields();
  form.value = {
    articleTitle: '',
    articleContent: '',
    articleImg: '',
    articleExcerpt: '',
    categoryId: null,
    status: 0,
    editorType: 'rich'
  };
  editorType.value = 'rich';
};

// 生命周期钩子
onMounted(async () => {
  await fetchCategories();
  if (id.value) {
    await fetchArticleData();
  } else {
    // 新建文章时，确保编辑器类型同步
    form.value.editorType = editorType.value;
  }
});
</script>

<style lang="scss" scoped>
.article-editor-container {
  padding: 16px 0;
}

.editor-wrapper {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 200px);
  overflow: auto;
  position: relative;
}

.editor-toolbar-sticky {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
  padding: 10px;
}

.editor-switch {
  margin-bottom: 10px;
  text-align: right;
  padding-right: 10px;
}

/* 面板切换标签 */
.panel-tabs {
  margin-bottom: 12px;
}

.tab-switch {
  display: flex;
  justify-content: center;
}

.ai-badge {
  margin-left: 4px;
}

/* 面板共有样式 */
.panel {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 240px);
  overflow: auto;
}

/* 表单面板样式 */
.metadata-wrapper {
  display: flex;
  flex-direction: column;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

/* AI建议面板样式 */
.ai-suggestions-wrapper {
  display: flex;
  flex-direction: column;
  padding: 16px;
}


.ai-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 12px;

  h3 {
    margin: 0;
    color: #303133;
  }
}

.ai-suggestions-content {
  flex: 1;
  overflow-y: auto;
}

.suggestion-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #eaeaea;

  &:last-child {
    border-bottom: none;
  }

}

.suggestion-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.suggestion-text {
  line-height: 1.8;
  white-space: pre-wrap;
  font-size: 14px;
  margin-top: 8px;
  color: #303133;
  padding: 0 4px;
}


.ai-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  gap: 16px;

  .cards {
    display: flex;
    gap: 10px;
  }

  .card {
    position: relative;
    width: 20px;
    height: 30px;
    perspective: 500px;
    animation: flip 2s infinite;
  }

  .card:nth-child(2) {
    animation-delay: 0.2s;
  }

  .card:nth-child(3) {
    animation-delay: 0.4s;
  }

  .card:nth-child(4) {
    animation-delay: 0.6s;
  }

  .face {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
    border-radius: 4px;
  }

  .front {
    background: #e67e22;
  }

  .back {
    background: #d35400;
    transform: rotateY(180deg);
  }

  @keyframes flip {

    0%,
    100% {
      transform: rotateY(0deg);
    }

    50% {
      transform: rotateY(180deg);
    }
  }
}

.ai-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  gap: 16px;
}

.w-full {
  width: 100%;
}
</style>